<?php

# Supress notice
@session_start();

require 'conf.php';

function error_msg($msg){
    echo json_encode(array('error' => $msg));
}


function change_password($sessiontoken, $old_password, $new_password){
    global $MW_host;
    $fields = array('USR_UPDATE_PASSWD' => '',
                    'SESSION' => $sessiontoken,
                    'OLD_PWD' => $old_password,
                    'NEW_PWD' => $new_password,);

    $fields = http_build_query($fields);

    $h = curl_init($MW_host);
    curl_setopt($h, CURLOPT_POST, 1);
    curl_setopt($h, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($h, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($h, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)));

   $res = curl_exec($h);
    
    if(!mb_check_encoding($res, 'UTF-8'))
        $res = utf8_encode($res);
    $data = json_decode($res);
    return $data;
}

if ($_POST['new_password'] != $_POST['new_password2']) {
    error_msg("Lösenordet överensstämmer inte");
} else if (strlen($_POST['new_password']) < 2) {
    error_msg("Lösenordet är för kort");
} else {
    $res = change_password($_SESSION['sessiontoken'], $_POST['old_password'], $_POST['new_password'], $_POST['new_password2']);
    if ($res === null) {
        error_msg("Ett fel uppstod i komunikationen med mellan-servern");
    } else {
        echo json_encode($res);
    }
}

?>
